package com.shs.riggy.filter;


import com.alibaba.fastjson.JSON;
import com.shs.riggy.common.BaseContext;
import com.shs.riggy.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 晚点再动心
 * @Date 2022/9/9
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取本次请求的路径
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}"+ request.getRequestURI());
            //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",  // 移动端 发送短信
                "/user/login"     //  移动端登录
        };
        //2.判断本次请求是否需要处理
        boolean checkURI = checkURI(urls, requestURI);
        //3.如果不需要处理直接放行
        if (checkURI){
            log.info("本次请求:{}不需要处理" + requestURI );
            filterChain.doFilter(request,response);
            return;
        }

        //4.1判断登录状态，如果是已经登录直接放行
        Long empId = (Long) request.getSession().getAttribute("employee");
        //将登陆用户的id存到ThreadLocal中，便于后面获取用户id
        BaseContext.setId(empId);
        if (empId != null){
            log.info("用户已经登录，用户id为:{}" ,empId);
            //如果session中能获取到用户，说明用户已经登录，直接放行
            filterChain.doFilter(request,response);
            return;
        }
        // 4-2、判断 移动端(消费者端)登录状态(session中含有employee的登录信息)，如果已经登录，则直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null){
            log.info("用户已经登录，用户id为:{}",userId);

            // 自定义元数据对象处理器 MyMetaObjectHandler中需要使用 登录用户id
            //   通过ThreadLocal set和get用户id
            BaseContext.setId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        //5.如果未登录则返回未登录结果,通过输出流的方式向客户端页面响应数据
        //响应的数据返回给前端的响应拦截器src/main/resources/backend/js/request.js
        log.info("用户未登录，返回到登录页面");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        //拦截之后对请求进行放行

    }

    //路径匹配，检查本次请求是否需要处理
    public boolean checkURI(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = ANT_PATH_MATCHER.match(url, requestURI);
            //与不需要的路径进行匹配，如果匹配到则放行
            if (match){
                return true;
            }
        }
        return false;
    }
}
